#include<bits/stdc++.h>
using namespace std;

#define maxn 310
#define MIN(x,y,t) if(x>=0 && x<maxn && y>=0 && y<maxn) death[x][y]=min(death[x][y],t)
int dx[4]= {0,0,1,-1};
int dy[4]= {1,-1,0,0};

struct node {
    int x,y;
};
int death[maxn][maxn];
int ans[maxn][maxn]; 
int main()
{
    int m, Ans=1e9;  
    cin>>m;
    int x,y,t;
    memset(ans,-1,sizeof(ans));
    memset(death,0x7f,sizeof(death));
    while(m--) {
        cin>>x>>y>>t;
        MIN(x,y,t);
        for(int i=0; i<4; i++) {  
            int nx=x+dx[i];
            int ny=y+dy[i];
            MIN(nx,ny,t);
        }
    }

    queue<node> q;
    ans[0][0] = 0; 
    q.push({0,0});
    while(!q.empty()) {
        node now=q.front();
        q.pop();
        for(int i=0; i<4; i++) {
            int nx=now.x+dx[i];
            int ny=now.y+dy[i];
            int current_time = ans[now.x][now.y] + 1;
            if(nx<0 || ny<0 || nx>=maxn || ny>=maxn || ans[nx][ny]!=-1 || current_time >= death[nx][ny]) {
                continue;
            }
            ans[nx][ny]=current_time;
            q.push({nx,ny});
        }
    }
    for(int i=0; i<maxn; i++){
        for(int j=0; j<maxn; j++){
            if(death[i][j] == 0x7f7f7f7f && ans[i][j]!=-1){ 
                Ans=min(Ans,ans[i][j]);
            }
        }
    }
    if(Ans == 1e9) cout<<-1<<endl;  
    else cout<<Ans<<endl;
    return 0;
}
